package com.xhs.hawaii.purchase.service;

import com.xhs.hawaii.common.BusinessException;
import com.xhs.hawaii.purchase.enums.PurchaseOrderTypeEnum;
import com.xhs.hawaii.purchase.mapper.PurchaseOrderLogMapper;
import com.xhs.hawaii.purchase.mapper.PurchaseOrderMapper;
import com.xhs.hawaii.purchase.model.PurchaseOrder;
import com.xhs.hawaii.purchase.model.PurchaseOrderLog;
import com.xhs.hawaii.purchase.vo.PurchaseOrderReceiveVo;
import com.xhs.hawaii.purchase.vo.PurchaseOrderSkuReceiveVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author tangchuang
 * @version 1.0
 * @since 2018/1/23
 */
@Service
@Slf4j
public class PurchaseOrderService {

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private PurchaseOrderLogMapper purchaseOrderLogMapper;

    @Autowired
    private PurchaseOrderSkuService purchaseOrderSkuService;

    @Transactional
    public void receivePurchaseOrderSku(PurchaseOrderReceiveVo purchaseOrderReceiveVo) {

        PurchaseOrder purchaseOrder = this.getByPurchaseOrderNo(purchaseOrderReceiveVo.getPurchaseOrderNo());

        BigDecimal payableAmount = BigDecimal.valueOf(0, 2);
        purchaseOrderReceiveVo.getPurchaseOrderSkuReceiveVoList()
                .stream()
                .map(t -> t.getPurchasePrice().multiply(new BigDecimal(t.getArriveNum())))
                .reduce(payableAmount, BigDecimal::add, BigDecimal::add);

        if (purchaseOrder == null) {
            purchaseOrder.setCreatorId(purchaseOrderReceiveVo.getCreatorId());
            purchaseOrder.setCreatorName(purchaseOrderReceiveVo.getCreatorName());
            purchaseOrder.setProviderCode(purchaseOrderReceiveVo.getProviderCode());
            purchaseOrder.setLogistic(purchaseOrderReceiveVo.getLogistic());
            purchaseOrder.setShippingAmount(purchaseOrderReceiveVo.getShippingAmount());
            purchaseOrder.setPurchaseNum(purchaseOrderReceiveVo.getPurchaseNum());
            purchaseOrder.setPurchaseAmount(purchaseOrderReceiveVo.getPurchaseAmount());
            purchaseOrder.setPurchaseOrderType(PurchaseOrderTypeEnum.NORMAL.name());
            purchaseOrder.setPurchaseAgent(purchaseOrderReceiveVo.getPurchaseAgent());
            purchaseOrder.setWhCode(purchaseOrderReceiveVo.getWhCode());
            purchaseOrder.setSettleType(purchaseOrderReceiveVo.getSettleType());
            purchaseOrder.setPayableAmount(payableAmount);
            purchaseOrder.setCurrency(purchaseOrderReceiveVo.getCurrency());
            purchaseOrder.setExchangeRate(purchaseOrderReceiveVo.getExchangeRate());
            BigDecimal prepayRate = purchaseOrderReceiveVo.getPrepayRate();

            purchaseOrder.setPrepayRate(prepayRate);
            purchaseOrder.setStage(2);

            if (prepayRate != null && prepayRate.compareTo(BigDecimal.ONE) == -1) {
                purchaseOrder.setStage(1);
            }

            this.insert(purchaseOrder);
        } else {
            purchaseOrder.setPayableAmount(purchaseOrder.getPayableAmount().add(payableAmount));
            int updateNum = this.update(purchaseOrder);
            if (updateNum == 0) {
                throw new BusinessException("并发异常");
            }
        }

        for (PurchaseOrderSkuReceiveVo purchaseOrderSkuReceiveVo : purchaseOrderReceiveVo.getPurchaseOrderSkuReceiveVoList()) {
            purchaseOrderSkuService.receivePurchaseOrderSku(purchaseOrder, purchaseOrderSkuReceiveVo);
        }

        // 判断是否生成付款记录 如果是预付款，直接生成，如果是账期，采购数量与实际到货数量一致
        if (Objects.equals("", purchaseOrder.getSettleType())) {
            // 预付款
        } else {
            // 账期
            if (Objects.equals(purchaseOrder.getArriveNum(),purchaseOrder.getPurchaseNum())){

            }
        }
    }

    public PurchaseOrder getById(Long id) {
        return purchaseOrderMapper.getById(id);
    }

    public PurchaseOrder getByPurchaseOrderNo(String purchaseOrderNo) {
        return purchaseOrderMapper.getByPurchaseOrderNo(purchaseOrderNo);
    }

    public void insert(PurchaseOrder purchaseOrder) {
        try {
            purchaseOrderMapper.insert(purchaseOrder);
        } catch (DataIntegrityViolationException e) {
            log.error("采购单号重复", e);
            throw new BusinessException("主键重复,并发异常");
        }
    }

    public int update(PurchaseOrder purchaseOrder) {
        if (purchaseOrderMapper.update(purchaseOrder) == 1) {
            purchaseOrder.setVersion(purchaseOrder.getVersion() + 1);
            return 1;
        }
        return 0;
    }

    public void insertLog(PurchaseOrderLog purchaseOrderLog) {
        purchaseOrderLogMapper.insert(purchaseOrderLog);
    }

    public List<PurchaseOrderLog> getLogsByPurchaseId(Long purchaseId) {
        return purchaseOrderLogMapper.getByPurchaseId(purchaseId);
    }

    public int getManualPoCount(Map<String, Object> params) {
        return purchaseOrderMapper.getManualPoCount(params);
    }

    public List<PurchaseOrder> getManualPoList(Map<String, Object> params) {
        return purchaseOrderMapper.getManualPoList(params);
    }
}
